package com.zaaach.citypicker;


import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.zaaach.citypicker.adapter.CityListAdapter;
import com.zaaach.citypicker.adapter.ResultListAdapter;
import com.zaaach.citypicker.db.DBDao;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.view.SideLetterBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Author Bro0cL on 2016/12/16.
 */
public class CityPickerActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String KEY_PICKED_CITY = "picked_city";
    public static final String KEY_PICKED_NAME = "picked_name";

    private ListView mListView;
    private ListView mResultListView;
    private SideLetterBar mLetterBar;
    private EditText searchBox;
    private ImageView clearBtn;
    private ImageView backBtn;
    private ViewGroup emptyView;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private List<City> mAllCities;
//    private DBManager dbManager;

    //    private AMapLocationClient mLocationClient;
    private String type;

    //    操作数据库
//    private DBDao dbDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cp_activity_city_list);
        type = getIntent().getExtras().getString("type");
        initData();
        initView();
        String city = getIntent().getStringExtra("city");
        if (!city.equals(""))
            mCityAdapter.updateLocateState(LocateState.SUCCESS, city);
        else
            mCityAdapter.updateLocateState(LocateState.FAILED, null);
//        initLocation();
    }

//    private void initLocation() {
//        mLocationClient = new AMapLocationClient(this);
//        AMapLocationClientOption option = new AMapLocationClientOption();
//        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        option.setOnceLocation(true);
//        mLocationClient.setLocationOption(option);
//        mLocationClient.setLocationListener(new AMapLocationListener() {
//            @Override
//            public void onLocationChanged(AMapLocation aMapLocation) {
//                if (aMapLocation != null) {
//                    Log.e("sss", "ErrorCode--------------" + aMapLocation.getErrorCode());
//                    if (aMapLocation.getErrorCode() == 0) {
//                        String city1 = aMapLocation.getCity();
//                        mCityAdapter.updateLocateState(LocateState.SUCCESS, city1);
//                    } else {
//                        //定位失败
//                        mCityAdapter.updateLocateState(LocateState.FAILED, null);
//                    }
//                }
//            }
//        });
//        mLocationClient.startLocation();
//    }

    private void initData() {
        mAllCities = new ArrayList<>();
        if (type.equals("a")) {
//            readTextFromSDcard("city.json");
            readTextFromSDcard("city.json");
        } else if (type.equals("b")) {
            readTextFromSDcard("cityz_zhuce.json");
        }
    }


    /*
解析本地json 转换list
* this
* "minzu.json"
* */
    public void readTextFromSDcard(String jsonName) {
//创建数据库 表
//        dbDao = new DBDao(this);
//        dbDao.delete();
        mAllCities = new ArrayList<>();
        InputStreamReader inputStreamReader;
        try {
            inputStreamReader = new InputStreamReader(getResources().getAssets().open(jsonName));
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStreamReader.close();
            bufferedReader.close();
            String resultString = stringBuilder.toString();
            JSONObject json = new JSONObject(resultString);

            JSONArray listdata = json.getJSONArray("list");
            for (int i = 0; i < listdata.length(); i++) {
                JSONObject jsonObject = listdata.getJSONObject(i);
                JSONArray citys = jsonObject.getJSONArray("citys");
                for (int a = 0; a < citys.length(); a++) {
                    JSONObject jsonObject1 = citys.getJSONObject(a);
                    String domain = jsonObject1.getString("domain");
                    String id = jsonObject1.getString("id");
                    String name = jsonObject1.getString("name");
                    mAllCities.add(new City(name, domain, id));
//                    插入数据库
//                    dbDao.save(id, name, domain);
                }
            }
//            List<City> all = dbDao.findAll();
//            Log.i("查询数据库是否成功", all.get(0).toString());
//            Log.i("查询数据库数量", all.size() + "");

            mCityAdapter = new CityListAdapter(this, mAllCities);
            mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
                @Override
                public void onCityClick(String name) {
                    back(name);
                }

                @Override
                public void onLocateClick() {
                    mCityAdapter.updateLocateState(LocateState.LOCATING, null);
//                    mLocationClient.startLocation();
                }
            });

            mResultAdapter = new ResultListAdapter(this, null);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void initView() {
        mListView = (ListView) findViewById(R.id.listview_all_city);
        mListView.setAdapter(mCityAdapter);

        TextView overlay = (TextView) findViewById(R.id.tv_letter_overlay);
        mLetterBar = (SideLetterBar) findViewById(R.id.side_letter_bar);
        mLetterBar.setOverlay(overlay);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });


        searchBox = (EditText) findViewById(R.id.et_search);

        searchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    clearBtn.setVisibility(View.GONE);
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    clearBtn.setVisibility(View.VISIBLE);
                    mResultListView.setVisibility(View.VISIBLE);
//                    List<City> byAll = dbDao.findByAll(keyword);
                    List<City> byAll = new ArrayList<>();
                    byAll.clear();
                    for (int i = 0; i < mAllCities.size(); i++) {
                        if (mAllCities.get(i).getName().indexOf(keyword) != -1)
                            byAll.add(mAllCities.get(i));
                    }

                    if (byAll != null) {
                        for (int i = 0; i < byAll.size(); i++) {
                            Log.i("查询的城市", byAll.get(i).getName());
                        }
                        if (byAll == null || byAll.size() == 0) {
                            emptyView.setVisibility(View.VISIBLE);
                        } else {
                            emptyView.setVisibility(View.GONE);
                            mResultAdapter.changeData(byAll);
                        }
                    } else {
                        Log.i("查询的城市空", byAll + "");
                    }

                }
            }
        });

        emptyView = (ViewGroup) findViewById(R.id.empty_view);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                back(mResultAdapter.getItem(position).getId() + "&" + mResultAdapter.getItem(position).getName());
            }
        });

        clearBtn = (ImageView) findViewById(R.id.iv_search_clear);
        backBtn = (ImageView) findViewById(R.id.back);

        clearBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
    }

    private void back(String city) {
        String name = city.substring(city.lastIndexOf("&") + 1);
        String citycode = city.substring(0, city.lastIndexOf("&"));
        Log.i("城市名;", city);
        Log.i("城市名;", name);
        Log.i("城市名citycode;", citycode);
        Intent data = new Intent();
        data.putExtra(KEY_PICKED_CITY, citycode);
        data.putExtra(KEY_PICKED_NAME, name);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_search_clear) {
            searchBox.setText("");
            clearBtn.setVisibility(View.GONE);
            emptyView.setVisibility(View.GONE);
            mResultListView.setVisibility(View.GONE);
        } else if (i == R.id.back) {
            finish();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mLocationClient.stopLocation();
    }
}
